import { login, logout, init } from '@/api/auth/userApi'
import { getToken, setToken, removeToken } from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg'
import Layout from '@/layout/index.vue'
import ParentView from '@/components/ParentView/index.vue'
import InnerLink from '@/layout/components/InnerLink/index.vue'
import router, { constantRoutes } from '@/router'
import { isHttp } from '@/utils/validate'
// 匹配views里面所有的.vue文件
const modules = import.meta.glob('./../../views/**/*.vue')

const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    dept: '',
    name: '',
    avatar: '',
    leftMenu: [],
    topMenu: [],
    routes: []
  }),
  actions: {
    // 登录
    login(userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then((data) => {
            const { token = '' } = data
            setToken(token)
            this.token = token
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 初始化
    init() {
      return new Promise((resolve, reject) => {
        init()
          .then((res) => {
            const { user, leftMenu, topMenu } = res
            const avatar = !user.avatar ? defAva : import.meta.env.VITE_APP_BASE_API + user.avatar
            this.name = user.name
            this.avatar = avatar
            //深拷贝
            const leftData = JSON.parse(JSON.stringify(leftMenu))
            const topData = JSON.parse(JSON.stringify(topMenu))
            const left = filterAsyncRouter(leftData, false, true)
            const top = filterAsyncRouter(topData, false, true)
            left.forEach((route) => {
              if (!isHttp(route.path)) {
                router.addRoute(route)
              }
            })
            top.forEach((route) => {
              if (!isHttp(route.path)) {
                router.addRoute(route)
              }
            })
            this.setInitMenu(left, top)
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 退出系统
    logOut() {
      return new Promise((resolve, reject) => {
        logout(this.token)
          .then(() => {
            this.token = ''
            this.leftMenu = []
            this.topMenu = []
            removeToken()
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    setInitMenu(leftMenu, topMenu) {
      this.leftMenu = leftMenu
      this.topMenu = topMenu
      this.routes = constantRoutes.concat(leftMenu).concat(topMenu)
    }
  }
})

function filterAsyncRouter(asyncRouterMap) {
  return asyncRouterMap.filter((route) => {
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else if (route.component === 'InnerLink') {
        route.component = InnerLink
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

export const loadView = (view) => {
  let res
  for (const path in modules) {
    const dir = path.split('views/')[1].split('.vue')[0]
    if (dir === view) {
      res = () => modules[path]()
    }
  }
  return res
}

export default useUserStore
